import logging
import threading
from DrissionPage import ChromiumOptions, ChromiumPage


def set_base_config():
    path = r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
    co = ChromiumOptions().set_paths(browser_path=path)
    return co


class OpenWebPage(object):
    listen_targets = ['web/v1/search/notes', 'api/sns/web/v1/feed']

    search_xpath = 'xpath://*[@id="search-input"]'

    search_button_xpath = 'xpath://div[@class="search-icon"]'

    end_xpath = 'xpath://div[@class="end-container"]'

    section_xpath = 'xpath://section'

    close_section_xpath = 'xpath://div[@class="close close-mask-dark"]'

    def __init__(self, url):
        co = set_base_config()
        self.web_page = ChromiumPage(co)
        self.web_page.listen.start(targets=self.listen_targets)
        self.web_page.get(url)

    def search_notes(self, keywords):
        search = self.web_page.ele(self.search_xpath)
        if not search:
            logging.error(f'No results found for {self.search_xpath}')
        search.input(keywords)
        self.web_page.ele(self.search_button_xpath).click()

    def get_section_len(self):
        return len(self.web_page.ele(self.section_xpath))

    def click_section(self, count):
        self.web_page.eles(self.section_xpath)[count].click()

    def close_section(self):
        self.web_page.ele().click()

    def scroll_screen(self):
        self.web_page.scroll.to_bottom()

    def has_more_pages(self):
        end = self.web_page.ele(self.end_xpath)
        if not end:
            logging.info("has more page")
            return True
        else:
            logging.info("has no pages")
            return False

    def wait_data_async(self):
        thread = threading.Thread(target=self.wait_data())
        thread.start()

    def wait_data(self):
        while True:
            packet = self.web_page.listen.wait()
            print(packet.response.body)
            # with open(self.file_name, 'wd', encoding='utf-8') as file:
            #     file.write(packet.response.body)


op = OpenWebPage('https://www.xiaohongshu.com')
op.search_notes('胃癌')
has_more = True
num = 0
while has_more:
    if num == 2:
        op.scroll_screen()
    op.wait_data()
    for note in range(num, op.get_section_len()):
        op.click_section(note)
        op.wait_data()
        op.close_section()
        num += 1
    op.scroll_screen()
    has_more = op.has_more_pages()
